import datetime
from google.appengine.ext import db
from google.appengine.api import users

class Categories(db.Model):
    index = db.IntegerProperty(required=True)
    en    = db.StringProperty(required=True)
    ja    = db.StringProperty(required=True)

class SampleData(db.Model):
    index       = db.IntegerProperty(required=True)
    category    = db.ReferenceProperty(reference_class=Categories,required=True)
    pattern     = db.TextProperty(required=True)
    title       = db.TextProperty(required=True)
    description = db.TextProperty(required=True)
    user        = db.UserProperty(auto_current_user_add=True)
    published   = db.DateTimeProperty(auto_now_add=True)
    last_update = db.DateTimeProperty()
    def jst_published(self):
        return toJST(self.published)
    def jst_last_update(self):
        return toJST(self.last_update) if self.last_update else ''


def getModelMaxIndex(model):
    return db.GqlQuery('SELECT * FROM %s ORDER BY index DESC LIMIT 1' % model.entity_type()).get().index



def get_sign_link(url):
    if users.get_current_user():
        ret = {'login_link': users.create_logout_url(url),
               'login_text': 'sign out'}
    else:
        ret = {'login_link': users.create_login_url(url),
               'login_text': 'sign in'}
    return ret



class JST(datetime.tzinfo):
    def utcoffset(self,dt):
        return datetime.timedelta(hours=9)
    def dst(self,dt):
        return datetime.timedelta(0)
    def tzname(self,dt):
        return 'JST'


class UTC(datetime.tzinfo):
    def utcoffset(self, dt):
        return datetime.timedelta(0)
    def dst(self, dt):
        return datetime.timedelta(0)
    def tzname(self, dt):
        return 'UTC'



def toJST(value):
    if not value:
        value = datetime.datetime.now()
    
    value = value.replace(tzinfo=UTC()).astimezone(JST())
    return value


#This decorator allows RequestHandlers to receive get/post parameters as named arguments
def kwargs(original_func):
    import inspect
    argspec = inspect.getargspec(original_func) 
    args = tuple(argspec[0][1:])
    def decorated_func(rh):
        kwargs = dict([(arg, rh.request.get(arg)) for arg in args])
        return original_func(rh, **kwargs)
    
    return decorated_func
